package com.vip.seata.at.business.util;

import brave.Tracer;
import brave.Tracing;
import brave.propagation.ExtraFieldPropagation;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

public class SleuthHelper {

    public static final String SLEUTH_DEFAULT_BAGGAGE = "sleuth-baggage";

    /**
     * 获取 Sleuth 链路 Extra Meta 信息
     */
    public static Map<String, String> getBaggage() {
        String baggage = ExtraFieldPropagation.get(SLEUTH_DEFAULT_BAGGAGE);
        if (StringUtils.isNotEmpty(baggage)) {
            return JSON.parseObject(baggage, new TypeReference<HashMap<String, String>>() {
            });
        }
        return null;
    }

    public static String getBaggageValue(String key) {
        Map<String, String> baggage = getBaggage();
        if(baggage!=null){
            return baggage.get(key);
        }
        return null;
    }

    /**
     * 设置 Sleuth 链路 Extra Meta 信息
     */
    public static void addBaggage(String key, String value) {
        Map<String, String> baggage = getBaggage();
        if (baggage==null) {
            baggage = new HashMap<>();
        }
        baggage.put(key, value);
        ExtraFieldPropagation.set(SLEUTH_DEFAULT_BAGGAGE, JSON.toJSONString(baggage));
    }

    /**
     * 获取 Sleuth 的 TraceId
     */
    public static String getSleuthTraceId() {
        Tracer tracer = Tracing.currentTracer();
        if (ObjectUtils.isEmpty(tracer)) {
            return StringPool.EMPTY;
        }
        return tracer.currentSpan().context().traceIdString() + StringPool.DOT+tracer.currentSpan().context().spanIdString();
    }
}
